<template>
  <view class="history-container">
    <!-- 顶部导航栏 -->
    <view class="history-header">
      <text class="title">浏览记录</text>
      <view class="header-actions">
        <text class="clear-btn" @click="showClearConfirm">清空</text>
      </view>
    </view>

    <!-- 时间筛选 -->
    <view class="time-filter">
      <text 
        v-for="(item, index) in timeFilters" 
        :key="index"
        :class="['filter-item', {active: activeFilter === item.value}]"
        @click="changeFilter(item.value)"
      >
        {{item.label}}
      </text>
    </view>

    <!-- 浏览记录列表 -->
    <scroll-view class="history-list" scroll-y="true" @scrolltolower="loadMore">
      <view 
        v-for="(item, index) in filteredHistory" 
        :key="item.id" 
        class="history-item"
        @click="viewDetail(item)"
      >
        <image class="cover" :src="item.cover" mode="aspectFill"></image>
        <view class="info">
          <text class="title">{{item.title}}</text>
          <text class="author">{{item.author}}</text>
          <view class="meta">
            <text class="time">{{formatTime(item.viewTime)}}</text>
            <text class="type">{{item.type}}</text>
          </view>
        </view>
        <view class="actions">
          <uni-icons 
            type="close" 
            size="18" 
            color="#999" 
            @click.stop="removeItem(item.id)"
          ></uni-icons>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <text>{{loading ? '加载中...' : '上拉加载更多'}}</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-tips" v-if="filteredHistory.length === 0">
        <image src="/static/404.png" mode="widthFix"></image>
        <text>暂无浏览记录</text>
        <button class="explore-btn" @click="goExplore">去发现好书</button>
      </view>
    </scroll-view>

    <!-- 清除确认弹窗 -->
    <uni-popup ref="clearPopup" type="dialog">
      <uni-popup-dialog 
        type="warn" 
        title="确认清空" 
        content="确定要清空所有浏览记录吗？" 
        :duration="2000" 
        :before-close="true" 
        @confirm="clearHistory" 
        @close="closeClearConfirm"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeFilter: 'all',
      timeFilters: [
        { label: '全部', value: 'all' },
        { label: '今天', value: 'today' },
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' }
      ],
      historyList: [
        {
          id: 1,
          title: '如何阅读一本书',
          author: '莫提默·J·艾德勒',
          cover: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.IRQ9ZU1Q0XdwtttUP0-MzwAAAA?w=120&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
          type: '书籍',
          viewTime: new Date().getTime(),
          duration: 120
        },
        {
          id: 2,
          title: '活着',
          author: '余华',
          cover: 'https://img13.360buyimg.com/n0/jfs/t17410/49/1720742472/193058/e66fc487/5ad5c2e3N28db4e91.jpg',
          type: '书籍',
          viewTime: new Date(Date.now() - 86400000).getTime(), // 昨天
          duration: 45
        },
        {
          id: 3,
          title: '高效阅读的七个习惯',
          author: '阅读研究所',
          cover: 'https://tse2-mm.cn.bing.net/th/id/OIP-C._7TeCed5679PoEhOaqcNyQHaFM?rs=1&pid=ImgDetMain',
          type: '文章',
          viewTime: new Date(Date.now() - 86400000 * 3).getTime(), // 3天前
          duration: 8
        },
        {
          id: 4,
          title: '认知觉醒读书笔记',
          author: '我的笔记',
          cover: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.rpayOK6Q-oBgBIXHG8fFuwHaJ4?w=121&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
          type: '笔记',
          viewTime: new Date(Date.now() - 86400000 * 10).getTime(), // 10天前
          duration: 5
        },
        {
          id: 5,
          title: '2024年度必读书单',
          author: '书友推荐',
          cover: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.7iZnIU6idIaANHfkAi3IJgHaHa?rs=1&pid=ImgDetMain',
          type: '书单',
          viewTime: new Date(Date.now() - 86400000 * 30).getTime(), // 30天前
          duration: 3
        }
      ],
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10
    }
  },
  computed: {
    filteredHistory() {
      const now = new Date()
      let list = [...this.historyList]
      
      // 按时间筛选
      switch (this.activeFilter) {
        case 'today':
          const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
          list = list.filter(item => item.viewTime >= todayStart)
          break
        case 'week':
          const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay()).getTime()
          list = list.filter(item => item.viewTime >= weekStart)
          break
        case 'month':
          const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).getTime()
          list = list.filter(item => item.viewTime >= monthStart)
          break
      }
      
      // 按分页筛选
      return list.slice(0, this.page * this.pageSize)
    }
  },
  methods: {
    changeFilter(value) {
      this.activeFilter = value
      this.page = 1
      this.hasMore = true
    },
    formatTime(timestamp) {
      const now = new Date()
      const date = new Date(timestamp)
      const diffDays = Math.floor((now - date) / 86400000)
      
      if (diffDays === 0) {
        return '今天'
      } else if (diffDays === 1) {
        return '昨天'
      } else if (diffDays < 7) {
        return `${diffDays}天前`
      } else if (diffDays < 30) {
        return `${Math.floor(diffDays / 7)}周前`
      } else {
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      }
    },
    viewDetail(item) {
      let url = ''
      switch (item.type) {
        case '书籍':
          url = `/pages/book-detail/book-detail?id=${item.id}`
          break
        case '文章':
          url = `/pages/article-detail/article-detail?id=${item.id}`
          break
        case '笔记':
          url = `/pages/note-detail/note-detail?id=${item.id}`
          break
        case '书单':
          url = `/pages/booklist-detail/booklist-detail?id=${item.id}`
          break
      }
      uni.navigateTo({ url })
    },
    removeItem(id) {
      const index = this.historyList.findIndex(item => item.id === id)
      if (index !== -1) {
        this.historyList.splice(index, 1)
        uni.showToast({ title: '已删除', icon: 'success' })
      }
    },
    showClearConfirm() {
      if (this.historyList.length === 0) {
        uni.showToast({ title: '没有可清除的记录', icon: 'none' })
        return
      }
      this.$refs.clearPopup.open()
    },
    closeClearConfirm() {
      this.$refs.clearPopup.close()
    },
    clearHistory() {
      this.historyList = []
      this.page = 1
      this.hasMore = false
      uni.showToast({ title: '已清空', icon: 'success' })
    },
    loadMore() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      // 模拟加载更多数据
      setTimeout(() => {
        const newItems = Array.from({length: 5}, (_, i) => ({
          id: this.historyList.length + i + 1,
          title: `测试书籍 ${this.historyList.length + i + 1}`,
          author: '测试作者',
          cover: 'https://tse1-mm.cn.bing.net/th/id/OIP-C.2NZhzUb6MFPMJH7gj61b_gHaE8?w=266&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
          type: '书籍',
          viewTime: new Date(Date.now() - 86400000 * (i + 5)).getTime(),
          duration: Math.floor(Math.random() * 60) + 1
        }))
        
        this.historyList = [...this.historyList, ...newItems]
        this.page += 1
        this.loading = false
        this.hasMore = this.page * this.pageSize < this.historyList.length + 10 // 模拟还有更多数据
      }, 1000)
    },
    showSearch() {
      uni.navigateTo({ url: '/pages/search/search?type=history' })
    },
    goExplore() {
      uni.switchTab({ url: '/pages/explore/explore' })
    }
  }
}
</script>

<style lang="scss">
.history-container {
  padding: 15px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  
  .title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    
    .clear-btn {
      font-size: 14px;
      color: #666;
      margin-right: 15px;
    }
    
    .uni-icons {
      margin-left: 15px;
    }
  }
}

.time-filter {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  
  .filter-item {
    padding: 6px 12px;
    margin-right: 10px;
    font-size: 14px;
    color: #666;
    border-radius: 15px;
    
    &.active {
      background-color: #2A5CAA;
      color: #fff;
    }
  }
}

.history-list {
  height: calc(100vh - 120px);
  
  .history-item {
    display: flex;
    background-color: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    
    .cover {
      width: 60px;
      height: 80px;
      border-radius: 4px;
      margin-right: 12px;
    }
    
    .info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .author {
        font-size: 12px;
        color: #666;
      }
      
      .meta {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: #999;
        
        .time {
          margin-right: 10px;
        }
        
        .type {
          background-color: #f0f0f0;
          padding: 2px 6px;
          border-radius: 3px;
        }
      }
    }
    
    .actions {
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-left: 10px;
    }
  }
  
  .load-more {
    text-align: center;
    padding: 15px 0;
    font-size: 14px;
    color: #999;
  }
  
  .empty-tips {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 0;
    
    image {
      width: 150px;
      height: 150px;
      margin-bottom: 20px;
    }
    
    text {
      font-size: 14px;
      color: #666;
      margin-bottom: 20px;
    }
    
    .explore-btn {
      background-color: #2A5CAA;
      color: #fff;
      border-radius: 20px;
      padding: 0 30px;
      font-size: 14px;
    }
  }
}
</style>